package com.fc.h5dispaly.h5display.util;

import android.os.SystemClock;
import android.util.Log;
import android.view.Choreographer;



import java.text.DecimalFormat;

/**
 * @Author: yuzhan
 */
public class FpsManager {

    public interface MyFpsCallback {
        void onFpsLoaded(float fps);
    }

    public static FpsManager instance = new FpsManager();

    private volatile boolean bRunning = false;
    private volatile float fps = 0f;
    private DecimalFormat decimalFormat = new DecimalFormat(".00");
    private FPSFrameCallback callback;
    private MyFpsCallback myCallback;

    private FpsManager(){
        callback = new FPSFrameCallback();
    }

    public void setMyCallback(MyFpsCallback cb) {
        this.myCallback = cb;
    }

    public void startFps() {
        if(bRunning) {
            return ;
        }
        Log.d("HomeFps", "+++++++ startFps");
        bRunning = true;
        Choreographer.getInstance().removeFrameCallback(callback);
        Choreographer.getInstance().postFrameCallback(callback);
    }

    public String getFormatFps() {
        return decimalFormat.format(fps);
    }

    public float getFps() {
        return fps;
    }

    public String formatFpsValue(float f) {
        return decimalFormat.format(f);
    }

    class FPSFrameCallback implements Choreographer.FrameCallback {
        private int frameCount;
        private long last;
        private long now;
        private long INTERVAL = 1000;

        public FPSFrameCallback() {
        }

        @Override
        public void doFrame(long frameTimeNanos) {
            //绘制这一帧花费的时间
            frameCount++;
            now = SystemClock.uptimeMillis();
            if(now - last >= INTERVAL) {
                //超出1秒钟，开始计算
                fps = frameCount / ((float)((now-last))/1000);//计算这段时间内的fps
                frameCount = 0;
                last = now;
                //FPS是一秒钟可以绘制多少帧
                Log.d("HomeFps", "fps = " + decimalFormat.format(fps));
                if(myCallback != null)
                    myCallback.onFpsLoaded(fps);
            }
            if(bRunning) {
                Choreographer.getInstance().postFrameCallback(this);
            }
        }
    }
}
